var app = getApp();
var bmap = require('../budu-map/bmap-wx.min.js');
var wxMarkerData = [];
//index.js
Page({
  data: {
    'address': '定位中',
    ak: "AXMRrsEZ0CGfogyRENeexOTkHxauhZtz", //填写申请到的ak 
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    circular: true,
    proCat: [],
    page: 2,
    index: 2,
    brand: [],
    // 滑动
    imgUrl: [],
    contact: [],
    contactIndex: 0,
    pic_array: [],
    hx_index: 0,
    manufactorList: [],


    baseUrl: app.d.ceshiUrl,
    productData: [],
    imgUrls: [{
        selected: true,
        photo: 'http://39.104.123.0/image/time1.jpeg',
        stype: true
      },
      {
        selected: false,
        photo: 'http://39.104.123.0/image/time3.jpeg',
        stype: true
      },
      {
        selected: false,
        photo: 'http://39.104.123.0/image/time4.jpeg',
        stype: true
      },
      {
        selected: false,
        photo: 'http://39.104.123.0/image/time2.jpeg',
        stype: true
      },

    ],

    total: 0,
    carts: [],
    contractName: null,


    categories: [],
    isManufactor: false,


  },
  tofactor: function(e) {
    console.log("tofactor")
    let ids = e.target.dataset.id;
    console.log(e.target.dataset.id)
    let manufactorList = this.data.manufactorList
    for (var i = 0; i < manufactorList.length; i++) {
      var id=manufactorList[i].id;
      if (id == ids){
        let data = JSON.stringify(manufactorList[i])
        wx.navigateTo({
          url: '/pages/manufactor/factor?menu='+data,
        })
      }
    }
  },
  bindContactChange: function(e) {
    var that = this
    console.log('bindContactChange');
    var contactId = this.data.contact[e.detail.value].id;
    if (contactId == 0) {
      this.setData({
        isManufactor: true,
      });
      that.init();
    } else {
      this.setData({
        isManufactor: false,
      });
      that.init();
    }
    this.setData({
      contactIndex: e.detail.value
    });
    app.seclectContract(contactId);
  },

  bannergo: function(e) {
    var atype = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.action;
    if (atype == "product") {
      wx.navigateTo({
        url: '../product/detail?productId=' + id,
      })
    }
  },


  onLoad: function(options) {
    var that = this;
    if (app.globalData.isGetCookie == '') {
      setTimeout(function() {
        that.onLoad();
      }, 1000)
    } else {
      that.setData({
        contact: app.globalData.contact,
      });

      that.init()
      // that.getCat()
      console.log("this.data.contact")
      console.log(this.data.contact)
    }

  },
  onShow: function(e) {
    var that = this;
    that.getCat()
  },

  init: function() {
    var that = this;
    console.log(that.data.contact);
    // 分类
    wx.request({
      url: app.d.ceshiUrl + '/goods/GoodsClassMgrAction!list',
      method: 'post',
      data: {},
      header: app.globalData.header,
      success: function(res) {
        var rows = res.data.rows;
        app.globalData.carts = rows;
        that.setData({
          categories: rows,
        });
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })
    // 获取厂家
    wx.request({
      url: app.d.ceshiUrl + '/user/UserMgrAction!listManufacturer',
      method: 'post',
      data: {},
      header: app.globalData.header,
      success: function(res) {
        var rows = res.data.rows;
        console.log("获取厂家")
        console.log(res)
        app.globalData.carts = rows;
        that.setData({
          manufactorList: rows,
        });
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })

    // 获取商品
    wx.request({
      url: app.d.ceshiUrl + '/goods/GoodsMgrAction!list',
      method: 'post',
      data: {},
      header: app.globalData.header,
      success: function(res) {
        var rows = res.data.rows;
        app.globalData.carts = rows;
        console.log(res);
        that.setData({
          productData: rows,
        });
        that.getCat();
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })
    // 定位
    // var that = this;  
    /* 获取定位地理位置 */
    // 新建bmap对象   
    var BMap = new bmap.BMapWX({
      ak: that.data.ak,
    });
    // console.log(BMap)
    var fail = function(data) {
      console.log(data);
    };
    var success = function(data) {
      console.log(data)
      //使用wxMarkerData获取数据  
      //  = data.wxMarkerData;  
      var addressComponent = data.originalData.result.addressComponent
      var address = data.originalData.result.formatted_address
      var location = data.originalData.result.location;

      wx.setStorageSync('province', addressComponent.province)
      wx.setStorageSync('city', addressComponent.city)
      wx.setStorageSync('district', addressComponent.district)
      wx.setStorageSync('street', addressComponent.street)
      wx.setStorageSync('street_number', addressComponent.street_number)

      wx.setStorageSync('address', address)
      wx.setStorageSync('location', location)



      wxMarkerData = data.originalData.result.addressComponent.city
      //把所有数据放在初始化data内  
      console.log(wxMarkerData)
      that.setData({
        // markers: wxMarkerData,
        // latitude: wxMarkerData[0].latitude,  
        // longitude: wxMarkerData[0].longitude,  
        address: wxMarkerData
      });
    }
    // 发起regeocoding检索请求   
    BMap.regeocoding({
      fail: fail,
      success: success
    });
  },

  restaurantsOfCategory: function(e) {
    console.log(e)
    var catid = e.currentTarget.dataset.category.id;
    wx.navigateTo({
      url: '/pages/category/index?id=' + catid
    })
  },

  onShareAppMessage: function() {
    return {
      title: '送气平台服务中心',
      path: '/pages/index/index',
      success: function(res) {
        // 分享成功
      },
      fail: function(res) {
        // 分享失败
      }
    }
  },
  //点击加载更多
  getMore: function(e) {
    var that = this;
    console.log(that.data.contact);
    wx.request({
      url: app.d.ceshiUrl + '/goods/GoodsMgrAction!list',
      method: 'post',
      data: {},
      header: app.globalData.header,
      success: function(res) {
        var rows = res.data.rows;
        app.globalData.carts = rows;
        // console.log(res);
        // console.log("proList");
        that.setData({
          productData: rows,
        });
        that.getCat();
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })
  },

  // 获取购物车数据
  getCat: function() {
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/StoreCartMgrAction!listGoods',
      method: 'post',
      header: app.globalData.header,
      success: function(res) {
        // console.log(res)
        var cart = res.data.rows;
        var prolist = that.data.productData
        var total = 0;
        // console.log('getCat')
        // console.log(res)
        if (res.data.success == 'false') {
          cart = ''
          that.setData({
            carts: [],
          });
        }
        if (cart == '') {
          for (let i = 0; i < prolist.length; i++) {
            prolist[i].count = 0;
          }
          that.setData({
            carts: [],
            productData: prolist,
          });
          return
        }

        for (let i = 0; i < prolist.length; i++) {
          for (let j = 0; j < cart.length; j++) {
            if (prolist[i].id == cart[j].goods_id) {
              prolist[i].count = cart[j].count;
              prolist[i].cartid = cart[j].id;
              break;
            } else {
              prolist[i].count = 0;
            }
          }
        }
        that.setData({
          productData: prolist,
          contractName: res.data.contract_name,
          carts: cart,
          total: total
        });
        console.log(that.data.contractName);

      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    });
  },

  bindMinus: function(e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.productData[index].count;
    var cartid = e.currentTarget.dataset.cartid;
    if (num == 1) {
      e = {
        'cartid': cartid,
      };
      that.removeShopCard(e)
    }
    if (num > 1) {
      num--;
      e = {
        'cartid': cartid,
        'num': num,
        'index': index
      };
      that.updataNum(e);
    }

    console.log(num);



  },
  bindManual: function(e) {
    console.log(e)
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = e.detail.value;
    var cartid = e.currentTarget.dataset.cartid;
    console.log(num);
    console.log(index);
    e = {
      'cartid': cartid,
      'num': num,
      'index': index
    };
    that.updataNum(e);


  },

  bindPlus: function(e) {
    var that = this;
    console.log('bindPlus')
    console.log(e)
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.productData[index].count;
    var price = that.data.productData[index].goods_price;
    var goodsid = that.data.productData[index].id;
    var cartid = e.currentTarget.dataset.cartid;
    if (num == 0) {
      var a = {
        'goodsid': goodsid,
        'price': price,
      };
      that.addToCat(a)
    } else {
      num++;
      console.log(num);
      e = {
        'cartid': cartid,
        'num': num,
        'index': index
      };
      that.updataNum(e);
    }
  },
  updataNum: function(e) {
    var that = this;
    var cartid = e.cartid;
    var num = e.num;
    var index = e.index;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/GoodsCartMgrAction!update',
      method: 'get',
      data: {
        'goodsCart.id': cartid,
        'goodsCart.count': num,
      },
      header: app.globalData.header,
      success: function(res) {
        var status = res.data.success;
        console.log(res)
        if (status == 'true') {
          // 只有大于一件的时候，才能normal状态，否则disable状态
          var minusStatus = num <= 1 ? 'disabled' : 'normal';
          // 购物车数据
          var produces = that.data.productData;
          produces[index].count = num;
          // 按钮可用状态
          // var minusStatuses = that.data.minusStatuses;
          // minusStatuses[index] = minusStatus;
          that.setData({
            // minusStatuses: minusStatuses,
            productData: produces
          });
          // that.sum();
        } else {
          wx.showToast({
            title: '操作失败！',
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },
  addToCat: function(e) {
    var goodsid = e.goodsid;
    var price = e.price;
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/StoreCartMgrAction!addGoods',
      method: 'get',
      data: {
        "goodsCart.goods.id": goodsid,
        'goodsCart.count': 1,
        'goodsCart.price': price,
      },
      header: app.globalData.header,
      success: function(res) {
        var data = res.data;
        console.log(res)
        console.log(res.data.msg);
        that.getCat();
        if (data.success == 'false') {
          wx.showToast({
            title: '请重新登录',
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },
  removeShopCard: function(e) {
    var that = this;
    var cardId = e.cartid;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/GoodsCartMgrAction!del',
      method: 'get',
      data: {
        'goodsCart.id': cardId,
      },
      header: app.globalData.header,
      success: function(res) {
        console.log(res)
        var data = res.data;
        if (data.success == 'true') {
          that.getCat()
        } else {
          wx.showToast({
            title: '操作失败！',
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },

});